# ../addons/manilib/core/clients/client.py

'''
$Rev: 6 $
$Author: pitkley $
$Date: 2009-11-01 11:19:13 +0000 (Sun, 01 Nov 2009) $
'''

# ==============================================================================
# >> IMPORTS
# ==============================================================================
# EventScripts Imports
import playerlib

# Manilib Imports
from manilib.core.clients.flags import AdminFlagsList

# ==============================================================================
# >> GLOBALS
# ==============================================================================
dict_mClients = {}
mAttributes = ["id", "name", "steamid", "adminflags", "immunityflags", \
    "admingroups", "immunitygroups", "adminlevels", "immunitylevels"]

# ==============================================================================
# >> FUNCTIONS
# ==============================================================================
def _add_client(maniid, name, steam):
    dict_mClients[maniid]               = {}
    dict_mClients[maniid]["steamid"]    = steam
    dict_mClients[maniid]["name"]       = name
    dict_mClients[maniid]["adminflags"] = AdminFlagsList(maniid)
    return Client(maniid)

def _get_client(id):
    """
    !Get the client for the id
    @param id The userid, steamid or the maniid for the mani client
    @return The client
    """
    return Client(id)

def _get_mani_id(id):
    """
    !Get the maniid of a mani client
    @param id The userid, steamid or the maniid for the mani client
    @return The maniid if available
    """
    if id in dict_mClients:
        return id
    else:
        if type(id).__name__ == "int":
            steamid = playerlib.uniqueid(id)
        elif id[0:6].upper() == "STEAM_":
            steamid = id
        else:
            raise ManilibError('Unable to get client with id "%s". ' % id +
                'No such client.')

        for maniid in dict_mClients:
            if dict_mClients[maniid]["steamid"] == steamid:
                return maniid

        raise ManilibError('Unable to get client with id "%s". ' % id +
                'No such client.')

def _is_client(id):
    try:
        maniid = _get_mani_id(id)
        return True
    except:
        return False
# ==============================================================================
# >> CLASSES
# ==============================================================================
class Client(object):
    """
    !Gets a mani client if available
    @param id The userid, the steamid or the maniid to get the client from
    """
    # ==========================================================================
    # >> Client() CLASS INITIALIZATION
    # ==========================================================================
    def __init__(self, id):
        self.id = _get_mani_id(id)

    # ==========================================================================
    # >> Client() CLASS USERLIST SUBCLASS
    # ==========================================================================
    # TODO userlist

    # ==========================================================================
    # >> Client() CLASS ATTRIBUTE METHODS
    # ==========================================================================
    def __getitem__(self, item):
        print "__getitem__"
        #return dict_mClients[self.id][item]
        return self.__getattr__(item)

    def __setitem__(self, item, value):
        print "__setitem__"
        #dict_mClients[self.id][item] = value
        self.__setattr__(item, value)

    def __getattr__(self, name):
        print "__getattr__: " + name
        if name == "id":
            object.__getattr__(self, name)
#        elif name in list_mCommands:
#            return self.Command(name)
        else:
            return dict_mClients[self.id][name]

    def __setattr__(self, name, value):
        if name not in mAttributes:
            raise AttributeError('Unable to set attribute "%s". ' % name +
                "This is not a attribute by Manilib.")
        elif name == "id":
            object.__setattr__(self, name, value)
        else:
            #if name == "adminflags":
            #    if not value in list_adminFlags:
            #        raise ManilibError('Couldn\'t')
            dict_mClients[self.id][name] = value
            print "__setattr__"

    def __delitem__(self, name):
        print "__delitem__"
        del dict_mClients[self.id][name]

    def __delattr__(self, name):
        print "__delattr__"
        raise AttributeError('Unable to delete attribute "%s". '
            % name + "This is a required attribute for Manilib.")

    # ==========================================================================
    # >> Client() CLASS COMMANDWRAPPER
    # ==========================================================================
    class Command(object): # Thanks to freddukes
        def __init__(self, command):
            self.command = command
        def __call__(self, *args):
            es.sexec("ma_%s %s %s" % (self.command, self.id, " ".join(map(str, args))))